from odoo import fields, models, api
from odoo.exceptions import UserError

WEB_ARTICLE_STATE = [('draft', '草稿'), ('complete', '完成')]


class RPWebArticle(models.Model):
    _name = 'rp.web.article'
    _description = "网站文章"
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _rec_name = "code"
    _sql_constraints = [('unique_name', 'UNIQUE(code)', '索引码重复')]
    _order = 'create_datetime desc'

    code = fields.Char(string='索引码', default='RP_AT/20240101/***', index=True, copy=False, readonly=True)
    create_datetime = fields.Datetime(string='创建时间', default=fields.Datetime.now, copy=False, readonly=True)
    publication_datetime = fields.Datetime(string='发布时间', default=fields.Datetime.now, copy=False, readonly=True, tracking=True)
    user_id = fields.Many2one(string='作者', comodel_name='res.users', default=lambda self: self.env.user, copy=False)
    state = fields.Selection(string='状态', selection=WEB_ARTICLE_STATE, default=WEB_ARTICLE_STATE[0][0], tracking=True)

    title = fields.Char(string='标题')
    subtitle = fields.Char(string='副标题')
    introduction = fields.Text(string='简介')
    suggested_reading_time_id = fields.Many2one(string='建议阅读时间', comodel_name='rp.suggested.reading.time')

    cover_image_ids = fields.Many2many(string='封面图', comodel_name='ir.attachment', column1='rp_web_article_id', column2='ir_attachment_id',
                                       relation='rp_web_article_ir_attachment_rel', copy=False)
    head_image_ids = fields.Many2many(string='头部图', comodel_name='ir.attachment', column1='web_article_id', column2='ir_attachment_id',
                                      relation='web_article_ir_attachment_rel', copy=False)

    category_id = fields.Many2one(string='分类', comodel_name='rp.web.article.category', required=True, tracking=True)
    industry_id = fields.Many2one(string='行业', comodel_name='rp.web.article.industry', required=True, tracking=True)
    tag_ids = fields.Many2many(string='标签', comodel_name='rp.web.article.tag',
                               relation='rp_web_article_and_tag_rel', column1='web_article_id', column2='tag_id', tracking=True)

    body = fields.Html(string='内容')

    relevance_article_ids = fields.Many2many(string='关联文章', comodel_name='rp.web.article',
                                             relation="rp_web_article_and_relevance_article_rel", column1='web_article_id', column2='relevance_article_id')

    publish_flag = fields.Boolean(string='发布', default=False, tracking=True)
    top_flag = fields.Boolean(string='置顶', default=False, tracking=True)

    @api.model_create_multi
    def create(self, vals):
        for val in vals:
            val['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.web.article') or '/'
        return super(RPWebArticle, self).create(vals)

    def write(self, vals):
        state = vals.get('state')
        if state == WEB_ARTICLE_STATE[0][0]:
            vals.update({'publish_flag': False, 'top_flag': False})
        return super(RPWebArticle, self).write(vals)

    def action_for_published(self):
        """ 发布 """
        self.ensure_one()
        if self.state == WEB_ARTICLE_STATE[1][0] and not self.publish_flag:
            return self.write({'publish_flag': True,
                               'publication_datetime': fields.Datetime.now()})

    def action_for_unpublished(self):
        """ 下架 """
        self.ensure_one()
        if self.state == WEB_ARTICLE_STATE[1][0] and self.publish_flag:
            return self.write({'publish_flag': False,
                               'top_flag': False,
                               'publication_datetime': False})

    def action_for_top(self):
        """ 置顶 """
        self.ensure_one()
        if self.publish_flag and not self.top_flag:
            return self.write({'top_flag': True})

    def action_for_notop(self):
        """ 取消置顶 """
        self.ensure_one()
        if self.publish_flag and self.top_flag:
            return self.write({'top_flag': False})
